package com.nuo.backend.modules.common.cos;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nuo.backend.common.exception.GlobalException;
import com.nuo.backend.common.utils.R;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.transfer.Download;
import com.qcloud.cos.transfer.TransferManager;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.UUID;

/**
 * @description: TODO 腾讯云文件操作
 * @author nuo
 * @date 2022/5/12 0:21
 * @version 1.0
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class COSServiceImpl implements COSService {

    public final COSClient cosClient;
    public final COSConfig cosConfig;

    @Override
    public R upload(MultipartFile[] fileArr) {
        JSONArray fileList = new JSONArray();
        Arrays.stream(fileArr).forEach(file -> {
            // 实例化json数据
            JSONObject jo = new JSONObject();

            String originalFilename = file.getOriginalFilename();
            String bucketName = cosConfig.getBucketName();
            String key = cosConfig.getPrefix()
                    + UUID.randomUUID().toString().replaceAll("-", "")
                    + originalFilename.substring(originalFilename.lastIndexOf('.'));
            try {
                //将 MultipartFile 类型 转为 File 类型
                File localFile = File.createTempFile("temp", null);
                file.transferTo(localFile);
                cosClient.putObject(new PutObjectRequest(bucketName, key, localFile));
                jo.put("fileUrl", cosConfig.getUrl() + key);
                jo.put("originalFilename", originalFilename);
                fileList.add(jo);

            } catch (Exception e) {
                throw new GlobalException("文件上传失败...");
            }

        });

        // 返回 json
        return R.ok("文件上传成功...").put("fileList" ,fileList);
    }

    @Override
    public R download(FilePO po) {
        TransferManager transferManager = null;
        try {
            //下载到本地指定路径
            File localDownFile = new File(po.getPath() + po.getFileName());
            GetObjectRequest getObjectRequest = new GetObjectRequest(cosConfig.getBucketName(), cosConfig.getPrefix() + po.getKey());
            // 下载文件
            transferManager = new TransferManager(cosClient);
            Download download = transferManager.download(getObjectRequest, localDownFile);
            // 等待传输结束 (如果想同步的等待上传结束，则调用 waitForCompletion)
            download.waitForCompletion();
        } catch (Throwable tb) {
            tb.printStackTrace();
            throw new GlobalException("下载失败...");
        } finally {
            // 关闭 TransferManger
            assert transferManager != null;
            transferManager.shutdownNow();
        }
        return R.ok();
    }


    @Override
    public R del(String key) {
        cosClient.deleteObject(cosConfig.getBucketName(), cosConfig.getPrefix() + key);
        return R.ok();
    }

}
